import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'dart:async';
import 'dart:io';

class CurrencyConverterPage extends StatefulWidget {
  const CurrencyConverterPage({super.key});

  @override
  State<CurrencyConverterPage> createState() => _CurrencyConverterPageState();
}

class _CurrencyConverterPageState extends State<CurrencyConverterPage> {
  String _amount = "0";
  String _fromCurrency = "USD";
  String _toCurrency = "CNY";
  Map<String, double> _exchangeRates = {};
  Map<String, String> _currencyNames = {};
  Timer? _rateUpdateTimer;
  String _expression = "";
  List<String> _history = [];
  bool _newNumber = true;
  String _lastUpdateDate = "";
  bool _isOnline = false; // 添加在线状态标志

  final List<String> _currencies = [
    "USD", // 美元
    "EUR", // 欧元
    "GBP", // 英镑
    "JPY", // 日元
    "CNY", // 人民币
    "AUD", // 澳元
    "CAD", // 加元
    "CHF", // 瑞士法郎
    "HKD", // 港元
    "SGD", // 新加坡元
    "KRW", // 韩元
    "INR", // 印度卢比
    "RUB", // 俄罗斯卢布
    "BRL", // 巴西雷亚尔
    "MXN", // 墨西哥比索
    "IDR", // 印尼盾
    "TRY", // 土耳其里拉
    "SAR", // 沙特里亚尔
    "AED", // 阿联酋迪拉姆
    "THB", // 泰铢
    "VND", // 越南盾
    "MYR", // 马来西亚林吉特
    "PHP", // 菲律宾比索
    "SEK", // 瑞典克朗
    "NOK", // 挪威克朗
    "DKK", // 丹麦克朗
    "PLN", // 波兰兹罗提
    "HUF", // 匈牙利福林
    "CZK", // 捷克克朗
    "ZAR", // 南非兰特
    "NZD", // 新西兰元
  ];

  @override
  void initState() {
    super.initState();
    // 先进行连接测试
    _testGiteeConnection().then((_) {
      // 测试完成后再获取汇率
      _fetchExchangeRates();
    });

    // 每5分钟更新一次汇率
    _rateUpdateTimer = Timer.periodic(const Duration(minutes: 5), (timer) {
      _fetchExchangeRates();
    });
  }

  @override
  void dispose() {
    _rateUpdateTimer?.cancel();
    super.dispose();
  }

  Future<void> _testGiteeConnection() async {
    try {
      final urls = [
        'https://gitee.com/zhishi22334/exchange_data/raw/master/exchange_rates.json',
        'http://gitee.com/zhishi22334/exchange_data/raw/master/exchange_rates.json'
      ];

      for (String url in urls) {
        try {
          print('测试连接到 $url');
          final response = await http.get(
            Uri.parse(url),
            headers: {
              'Accept': 'application/json',
              'User-Agent': 'Flutter-App',
            },
          ).timeout(
            const Duration(seconds: 10),
          );

          if (response.statusCode == 200) {
            setState(() {
              _isOnline = true;
            });
            print('连接成功！');
            print('响应状态码: ${response.statusCode}');
            return;
          }
        } catch (e) {
          print('测试 $url 时出错: $e');
          continue;
        }
      }

      setState(() {
        _isOnline = false;
      });
      print('所有连接测试都失败');
    } catch (e) {
      setState(() {
        _isOnline = false;
      });
      print('连接测试出错: $e');
    }
  }

  Future<void> _fetchExchangeRates() async {
    int maxRetries = 3;
    int currentTry = 0;

    while (currentTry < maxRetries) {
      try {
        // 使用不同的URL格式尝试访问
        final List<String> urls = [
          'https://gitee.com/zhishi22334/exchange_data/raw/master/exchange_rates.json',
          'http://gitee.com/zhishi22334/exchange_data/raw/master/exchange_rates.json', // 尝试HTTP
          'https://gitee.com/api/v5/repos/zhishi22334/exchange_data/contents/exchange_rates.json'
        ];

        Exception? lastError;
        for (String url in urls) {
          try {
            print('尝试连接到 $url');
            final response = await http.get(
              Uri.parse(url),
              headers: {
                'Accept': 'application/json',
                'User-Agent': 'Flutter-App',
              },
            ).timeout(
              const Duration(seconds: 10),
              onTimeout: () {
                print('连接超时，尝试下一个URL');
                throw TimeoutException('获取汇率数据超时');
              },
            );

            if (response.statusCode == 200) {
              try {
                print('成功获取响应');
                Map<String, dynamic> data;

                if (url.contains('api/v5')) {
                  // 如果是API URL，需要解码Base64
                  final responseData = json.decode(response.body);
                  final content = utf8.decode(base64
                      .decode(responseData['content'].replaceAll('\n', '')));
                  data = json.decode(content);
                } else {
                  // 直接解析JSON
                  data = json.decode(response.body);
                }

                if (data == null || !data.containsKey('currencies')) {
                  print('数据格式不正确: $data');
                  continue;
                }

                setState(() {
                  _isOnline = true;
                  _lastUpdateDate = data['date'] ?? '';
                  final currencies = data['currencies'] as Map<String, dynamic>;

                  // 更新汇率和货币名称
                  _exchangeRates.clear();
                  _currencyNames.clear();

                  currencies.forEach((key, value) {
                    if (value is Map<String, dynamic>) {
                      _exchangeRates[key] = (value['rate'] as num).toDouble();
                      _currencyNames[key] = value['name'] as String;
                    }
                  });

                  // 如果基准货币不是USD，需要转换所有汇率
                  if (_fromCurrency != 'USD') {
                    double baseRate = _exchangeRates[_fromCurrency] ?? 1.0;
                    _exchangeRates.forEach((key, value) {
                      _exchangeRates[key] = value / baseRate;
                    });
                  }
                });

                _convertCurrency();
                print('成功获取汇率数据: $_lastUpdateDate');
                return; // 成功获取数据后退出
              } catch (e) {
                print('解析数据时出错: $e');
                lastError = e as Exception;
                continue;
              }
            } else {
              print('请求失败: ${response.statusCode}');
              print('错误响应: ${response.body}');
              continue;
            }
          } catch (e) {
            print('请求 $url 时出错: $e');
            lastError = e as Exception;
            continue;
          }
        }

        // 如果所有URL都失败了，增加重试次数
        currentTry++;
        if (currentTry < maxRetries) {
          print('所有URL尝试失败，等待2秒后重试...');
          await Future.delayed(Duration(seconds: 2));
        } else {
          print('达到最大重试次数，使用备用数据');
          _useBackupRates();
          return;
        }
      } catch (e) {
        print('发生错误: $e');
        currentTry++;
        if (currentTry < maxRetries) {
          print('等待2秒后重试...');
          await Future.delayed(Duration(seconds: 2));
        } else {
          print('达到最大重试次数，使用备用数据');
          _useBackupRates();
          return;
        }
      }
    }
  }

  void _useBackupRates() {
    setState(() {
      _isOnline = false;
      _lastUpdateDate = DateTime.now().toString().split(' ')[0];

      // 使用基本的备用汇率数据
      _exchangeRates = {
        'USD': 1.0,
        'EUR': 0.92,
        'CNY': 7.23,
        'JPY': 149.5,
        'GBP': 0.79,
        'AUD': 1.52,
        'CAD': 1.35,
        'CHF': 0.88,
        'HKD': 7.82,
        'SGD': 1.34
      };

      _currencyNames = {
        'USD': '美元',
        'EUR': '欧元',
        'CNY': '人民币',
        'JPY': '日元',
        'GBP': '英镑',
        'AUD': '澳元',
        'CAD': '加元',
        'CHF': '瑞士法郎',
        'HKD': '港元',
        'SGD': '新加坡元'
      };
    });

    _convertCurrency();
  }

  void _convertCurrency() {
    if (_amount == "") return;

    try {
      double amount = double.parse(_amount);
      double rate = _exchangeRates[_toCurrency] ?? 1.0;
      double result = amount * rate;

      setState(() {
        _expression =
            "$_amount $_fromCurrency = ${result.toStringAsFixed(2)} $_toCurrency";
        if (!_history.contains(_expression)) {
          _history.add(_expression);
        }
      });
    } catch (e) {
      print('Error converting currency: $e');
    }
  }

  void _onCurrencyChange(String? newFromCurrency, String? newToCurrency) {
    setState(() {
      if (newFromCurrency != null && newFromCurrency != _fromCurrency) {
        _fromCurrency = newFromCurrency;
        _fetchExchangeRates(); // 当源货币改变时重新获取汇率
      } else if (newToCurrency != null && newToCurrency != _toCurrency) {
        _toCurrency = newToCurrency;
        _convertCurrency(); // 当目标货币改变时只需重新计算
      }
    });
  }

  void _onDigitPress(String digit) {
    setState(() {
      if (_newNumber) {
        _amount = digit;
        _newNumber = false;
      } else {
        _amount += digit;
      }
      _convertCurrency();
    });
  }

  void _onDecimalPress() {
    setState(() {
      if (_newNumber) {
        _amount = "0.";
        _newNumber = false;
      } else if (!_amount.contains(".")) {
        _amount += ".";
      }
    });
  }

  void _onClearPress() {
    setState(() {
      _amount = "0";
      _newNumber = true;
      _history.clear();
      _expression = "";
    });
  }

  void _onBackspace() {
    setState(() {
      if (_amount.length > 1) {
        _amount = _amount.substring(0, _amount.length - 1);
      } else {
        _amount = "0";
        _newNumber = true;
      }
      _convertCurrency();
    });
  }

  // 构建按钮方法
  Widget _buildButton(String text) {
    return Card(
      elevation: 2,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(8),
      ),
      child: InkWell(
        onTap: () {
          if (text == 'C') {
            setState(() {
              _amount = "0";
              _expression = "";
              _history.clear();
            });
          } else if (text == '.') {
            if (!_amount.contains('.')) {
              setState(() {
                _amount = _amount == "0" ? "0." : "$_amount.";
                _convertCurrency();
              });
            }
          } else {
            setState(() {
              _amount = _amount == "0" ? text : "$_amount$text";
              _convertCurrency();
            });
          }
        },
        borderRadius: BorderRadius.circular(8),
        child: Container(
          alignment: Alignment.center,
          child: Text(
            text,
            style: const TextStyle(
              fontSize: 24,
              fontWeight: FontWeight.w500,
            ),
          ),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.white,
        elevation: 1,
        title: const Text(
          '货币转换器',
          style: TextStyle(color: Colors.black87),
        ),
        actions: [
          Padding(
            padding: const EdgeInsets.all(8.0),
            child: Center(
              child: Row(
                children: [
                  Container(
                    width: 10,
                    height: 10,
                    decoration: BoxDecoration(
                      shape: BoxShape.circle,
                      color: _isOnline ? Colors.green : Colors.red,
                    ),
                  ),
                  const SizedBox(width: 8),
                  Text(
                    _isOnline ? '在线' : '离线',
                    style: const TextStyle(
                      fontSize: 14,
                      color: Colors.black87,
                    ),
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
      body: GestureDetector(
        behavior: HitTestBehavior.opaque,
        onTap: () {
          FocusManager.instance.primaryFocus?.unfocus();
        },
        child: SafeArea(
          child: Padding(
            padding: const EdgeInsets.all(16.0),
            child: Column(
              children: [
                Row(
                  children: [
                    Expanded(
                      child: Theme(
                        data: Theme.of(context).copyWith(
                          canvasColor: Colors.white,
                        ),
                        child: DropdownButtonHideUnderline(
                          child: Container(
                            decoration: BoxDecoration(
                              border: Border(
                                bottom: BorderSide(
                                  color: Colors.orange.withOpacity(0.8),
                                  width: 2,
                                ),
                              ),
                            ),
                            child: DropdownButton<String>(
                              value: _fromCurrency,
                              isExpanded: true,
                              icon: const Icon(Icons.arrow_drop_down),
                              iconEnabledColor: Colors.orange,
                              elevation: 1,
                              dropdownColor: Colors.white,
                              focusColor: Colors.transparent,
                              style: const TextStyle(
                                color: Colors.black87,
                                fontSize: 16,
                              ),
                              items: _currencies.map((String currency) {
                                return DropdownMenuItem<String>(
                                  value: currency,
                                  child: Text(
                                      '$currency (${_currencyNames[currency] ?? currency})'),
                                );
                              }).toList(),
                              onChanged: (String? newValue) {
                                if (newValue != null) {
                                  _onCurrencyChange(newValue, null);
                                  FocusManager.instance.primaryFocus?.unfocus();
                                }
                              },
                            ),
                          ),
                        ),
                      ),
                    ),
                    const Padding(
                      padding: EdgeInsets.symmetric(horizontal: 8.0),
                      child: Icon(Icons.arrow_forward, color: Colors.orange),
                    ),
                    Expanded(
                      child: Theme(
                        data: Theme.of(context).copyWith(
                          canvasColor: Colors.white,
                        ),
                        child: DropdownButtonHideUnderline(
                          child: Container(
                            decoration: BoxDecoration(
                              border: Border(
                                bottom: BorderSide(
                                  color: Colors.orange.withOpacity(0.8),
                                  width: 2,
                                ),
                              ),
                            ),
                            child: DropdownButton<String>(
                              value: _toCurrency,
                              isExpanded: true,
                              icon: const Icon(Icons.arrow_drop_down),
                              iconEnabledColor: Colors.orange,
                              elevation: 1,
                              dropdownColor: Colors.white,
                              focusColor: Colors.transparent,
                              style: const TextStyle(
                                color: Colors.black87,
                                fontSize: 16,
                              ),
                              items: _currencies.map((String currency) {
                                return DropdownMenuItem<String>(
                                  value: currency,
                                  child: Text(
                                      '$currency (${_currencyNames[currency] ?? currency})'),
                                );
                              }).toList(),
                              onChanged: (String? newValue) {
                                if (newValue != null) {
                                  _onCurrencyChange(null, newValue);
                                  FocusManager.instance.primaryFocus?.unfocus();
                                }
                              },
                            ),
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
                const SizedBox(height: 16),
                if (_lastUpdateDate.isNotEmpty)
                  Padding(
                    padding: const EdgeInsets.only(bottom: 8),
                    child: Text(
                      '最后更新: $_lastUpdateDate',
                      style: TextStyle(color: Colors.grey[600]),
                    ),
                  ),
                Padding(
                  padding: const EdgeInsets.symmetric(vertical: 16.0),
                  child: Text(
                    _expression,
                    style: const TextStyle(fontSize: 24),
                  ),
                ),
                const Spacer(),
                Container(
                  constraints: const BoxConstraints(maxHeight: 400),
                  child: AspectRatio(
                    aspectRatio: 3 / 4,
                    child: GridView.count(
                      crossAxisCount: 3,
                      childAspectRatio: 1.5,
                      mainAxisSpacing: 8,
                      crossAxisSpacing: 8,
                      physics: const NeverScrollableScrollPhysics(),
                      children: [
                        _buildButton('7'),
                        _buildButton('8'),
                        _buildButton('9'),
                        _buildButton('4'),
                        _buildButton('5'),
                        _buildButton('6'),
                        _buildButton('1'),
                        _buildButton('2'),
                        _buildButton('3'),
                        _buildButton('0'),
                        _buildButton('.'),
                        _buildButton('C'),
                      ],
                    ),
                  ),
                ),
                const SizedBox(height: 16),
              ],
            ),
          ),
        ),
      ),
    );
  }
}
